import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/modules/user'
import LoginPage from '../views/LoginPage.vue'
import MapLayout from '../views/MapLayout.vue'
import MapMonitor from '../views/MapMonitor.vue'
import RoadNetworkLayer from '../views/RoadNetworkLayer.vue'
import SignManagement from '../views/SignManagement.vue'
import Statistics from '../views/Statistics.vue'
import MaintenanceManagement from '../views/MaintenanceManagement.vue'
import AnalysisMaintenance from '../views/AnalysisMaintenance.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/login',
      name: 'login',
      component: LoginPage,
      meta: { requiresAuth: false },
    },
    {
      path: '/map',
      name: 'map',
      component: MapLayout,
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'mapMonitor',
          component: MapMonitor,
        },
        {
          path: 'road-network',
          name: 'roadNetwork',
          component: RoadNetworkLayer,
        },
        {
          path: 'sign-management',
          name: 'signManagement',
          component: SignManagement,
        },
        {
          path: 'statistics',
          name: 'statistics',
          component: Statistics,
        },
        {
          path: 'maintenance',
          name: 'maintenance',
          component: MaintenanceManagement,
        },
        {
          path: 'analysis-maintenance',
          name: 'analysisMaintenance',
          component: AnalysisMaintenance,
        },
      ],
    },
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

  // 如果需要认证且未登录，则重定向到登录页面
  if (requiresAuth && !userStore.isLogin) {
    next('/login')
  } else {
    // 如果已登录且访问登录页，则重定向到地图页面
    if (to.path === '/login' && userStore.isLogin) {
      next('/map')
    } else {
      next()
    }
  }
})

export default router
